package com.imooc.rabbitmq.consumer;

import java.util.Map;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import com.imooc.rabbitmq.entity.Order;
import com.rabbitmq.client.Channel;

@Component
public class OrderReceiver {
	
	// 绑定监听，可以在未配置的情况下，在平台自动生成
	@RabbitListener(bindings = @QueueBinding(
				value = @Queue(value = "order-queue",  
				durable="true"),
				exchange = @Exchange(value = "order-exchange",
				durable="true",
				type= "topic", 
				ignoreDeclarationExceptions = "true"),
				key = "order.*"
			)
	)
	
	// 手动签收必须依赖channel
	@RabbitHandler // 标识该方法，如果有消息过来，消费者调用该方法
	public void onOrderMessage(@Payload Order order, 
			@Headers Map<String, Object> headers, 
			Channel channel) throws Exception{
		// 消费者操作
		System.err.println("-----------------------收到消息，开始消费----------------------------");
		System.err.println("订单ID："+ order.getId());
		
		Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG) ;
		// ACK
		channel.basicAck(deliveryTag, false);
	}
	
}
